package com.yzc.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yzc.execption.ZcException;
import com.yzc.model.entity.ticket_order.OrderMain;
import com.yzc.result.Result;
import com.yzc.result.ResultCodeEnum;
import com.yzc.service.TicketMainOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/ticketOrder/mainOrder")
public class TicketMainOrderController {

    @Autowired
    private TicketMainOrderService service;

    @GetMapping("/users/{userId}/{pageNo}/{pageSize}")
    public Result<Page<OrderMain>> listOrders(
            @PathVariable("userId") Long userId,
            @PathVariable("pageNo") Integer pageNo,
            @PathVariable("pageSize") Integer pageSize
    ) {

        if (pageNo < 1 || pageSize < 1) {
            throw new ZcException(ResultCodeEnum.FAIL.getCode(),"分页参数必须大于0");
        }

        Page<OrderMain> page = new Page<>(pageNo, pageSize);
        Page<OrderMain> resultPage = service.listOrders(page, userId);

        return Result.success(resultPage);
    }

    @GetMapping("/detail/{orderId}")
    public Result<OrderMain> getOrderDetail(@PathVariable("orderId") Long orderId,
                                            @RequestHeader("userId") Long userId) {
        log.error("userId:{}, orderId:{}", userId, orderId);
        OrderMain order = service.getOrderDetail(orderId);
        if (order == null) {
            throw new ZcException(ResultCodeEnum.NOT_FOUND.getCode(), "订单不存在");
        }
        if (!order.getUserId().equals(userId)) {
            throw new ZcException(ResultCodeEnum.UNAUTHORIZED.getCode(), "无权访问此订单");
        }
        return Result.success(service.getOrderDetail(orderId));
    }

    @PostMapping("/cancel")
    public Result<Void> cancelOrder(@RequestBody OrderMain orderMain) {
        service.cancelOrder(orderMain.getOrderId(),orderMain.getUserId(), orderMain.getCancelReason());
        return Result.success();
    }
}
